"""
模型查询 API Router

提供模型列表查询、搜索、统计等功能
"""
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field

from src.llm.hiagent_app.services import ModelService, ModelInfo


# 响应模型
class ModelResponse(BaseModel):
    """模型信息响应"""
    model_id: str = Field(..., description="模型ID")
    model_name: str = Field(..., description="模型名称")
    usage_count: int = Field(..., description="使用次数")
    agents_using: List[str] = Field(..., description="使用该模型的智能体列表（最多显示5个）")


class ModelsListResponse(BaseModel):
    """模型列表响应"""
    success: bool = Field(True, description="是否成功")
    total: int = Field(..., description="模型总数")
    models: List[ModelResponse] = Field(..., description="模型列表")


class ModelStatisticsResponse(BaseModel):
    """模型统计响应"""
    success: bool = Field(True, description="是否成功")
    total_models: int = Field(..., description="模型总数")
    total_usage: int = Field(..., description="总使用次数")
    most_used_model: Optional[ModelResponse] = Field(None, description="最常用的模型")
    models: List[ModelResponse] = Field(..., description="所有模型列表")


# 创建路由
router = APIRouter(prefix="/api/v1/models", tags=["Models"])

# 创建服务实例
model_service = ModelService()


@router.get("/", response_model=ModelsListResponse, summary="获取可用模型列表")
async def get_models(
    use_cache: bool = Query(True, description="是否使用缓存"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    获取所有可用的模型列表

    - **use_cache**: 是否使用缓存（默认: true，缓存30分钟）
    - **workspace_id**: 工作空间ID（可选）

    返回按使用次数排序的模型列表
    """
    try:
        models = model_service.get_available_models(
            use_cache=use_cache,
            workspace_id=workspace_id
        )

        return ModelsListResponse(
            success=True,
            total=len(models),
            models=[
                ModelResponse(
                    model_id=model.model_id,
                    model_name=model.model_name,
                    usage_count=model.usage_count,
                    agents_using=model.agents_using[:5]  # 只返回前5个
                )
                for model in models
            ]
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取模型列表失败: {str(e)}")


@router.get("/{model_id}", response_model=ModelResponse, summary="根据ID获取模型信息")
async def get_model_by_id(
    model_id: str,
    use_cache: bool = Query(True, description="是否使用缓存"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    根据模型ID获取详细信息

    - **model_id**: 模型ID（例如: "d34idr85oc9ofekvmelg" 或 "doubao-seed-1-6"）
    - **use_cache**: 是否使用缓存
    - **workspace_id**: 工作空间ID（可选）
    """
    try:
        model = model_service.get_model_by_id(
            model_id=model_id,
            use_cache=use_cache,
            workspace_id=workspace_id
        )

        if not model:
            raise HTTPException(status_code=404, detail=f"模型不存在: {model_id}")

        return ModelResponse(
            model_id=model.model_id,
            model_name=model.model_name,
            usage_count=model.usage_count,
            agents_using=model.agents_using[:5]
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"查询模型失败: {str(e)}")


@router.get("/search/", response_model=ModelsListResponse, summary="搜索模型")
async def search_models(
    keyword: str = Query(..., description="搜索关键词", min_length=1),
    use_cache: bool = Query(True, description="是否使用缓存"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    搜索模型（支持模糊匹配）

    - **keyword**: 搜索关键词（匹配模型ID或名称）
    - **use_cache**: 是否使用缓存
    - **workspace_id**: 工作空间ID（可选）

    示例:
    - 搜索 "doubao" 返回所有豆包模型
    - 搜索 "pro" 返回所有 Pro 版本模型
    """
    try:
        models = model_service.search_models(
            keyword=keyword,
            use_cache=use_cache,
            workspace_id=workspace_id
        )

        return ModelsListResponse(
            success=True,
            total=len(models),
            models=[
                ModelResponse(
                    model_id=model.model_id,
                    model_name=model.model_name,
                    usage_count=model.usage_count,
                    agents_using=model.agents_using[:5]
                )
                for model in models
            ]
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"搜索模型失败: {str(e)}")


@router.get("/statistics/", response_model=ModelStatisticsResponse, summary="获取模型统计信息")
async def get_model_statistics(
    use_cache: bool = Query(True, description="是否使用缓存"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    获取模型使用统计信息

    - **use_cache**: 是否使用缓存
    - **workspace_id**: 工作空间ID（可选）

    返回:
    - 模型总数
    - 总使用次数
    - 最常用的模型
    - 所有模型列表
    """
    try:
        stats = model_service.get_model_statistics(
            use_cache=use_cache,
            workspace_id=workspace_id
        )

        most_used = None
        if stats.get('most_used_model'):
            most_used_data = stats['most_used_model']
            most_used = ModelResponse(
                model_id=most_used_data['model_id'],
                model_name=most_used_data['model_name'],
                usage_count=most_used_data['usage_count'],
                agents_using=most_used_data['agents_using'][:5]
            )

        return ModelStatisticsResponse(
            success=True,
            total_models=stats['total_models'],
            total_usage=stats['total_usage'],
            most_used_model=most_used,
            models=[
                ModelResponse(
                    model_id=model['model_id'],
                    model_name=model['model_name'],
                    usage_count=model['usage_count'],
                    agents_using=model['agents_using'][:5]
                )
                for model in stats['models']
            ]
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")


@router.post("/cache/clear", summary="清除缓存")
async def clear_cache():
    """
    清除模型缓存

    使用场景:
    - 需要强制刷新模型列表
    - 缓存数据过期
    """
    try:
        model_service.clear_cache()
        return {
            "success": True,
            "message": "缓存已清除"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"清除缓存失败: {str(e)}")
